package com.vf.admin.utils.Base64Image;

import com.vf.admin.utils.StringEx;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

public class ImageToBase {

    public static String strNetImageToBase64;

    public static ImageToBase getInstance(){
        return new ImageToBase();
    }
    public static void main(String[] args) {
        //第一个:把网络图片装换成Base64
        String netImagePath = "网络图片路径";
        //下面是网络图片转换Base64的方法
        // NetImageToBase64(netImagePath);

        //下面是本地图片转换Base64的方法
//        String imagePath = "D://aaa/1.jpg";
//        String basestr = ImageToBase.getInstance().ImageToBase64(imagePath);
//        System.out.println("basestr:"+basestr);
        String aa = "abcedf12asdf";
        aa = aa.substring(aa.indexOf("df12")+4,aa.length());
        System.out.println(aa);
    }

    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath     
     */
    public  void NetImageToBase64(String netImagePath) {
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is = conn.getInputStream();
                        // 将内容读取内存中
                        int len = -1;
                        while ((len = is.read(by)) != -1) {
                            data.write(by, 0, len);
                        }
                        // 对字节数组Base64编码
                        BASE64Encoder encoder = new BASE64Encoder();
                        strNetImageToBase64 = encoder.encode(data.toByteArray());
                        System.out.println("网络图片转换Base64:" + strNetImageToBase64);
                        // 关闭流
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath     
     */

    public String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            File imgFile = new File(imgPath);
            if(!imgFile.exists()){
                return "";
            }
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String resultStr = encoder.encode(data).trim().replaceAll("\n", "").replaceAll("\r", "");
//        String resultStr = encoder.encode(Objects.requireNonNull(data));
        // 返回Base64编码过的字节数组字符串
        System.out.println("本地图片转换Base64:" + resultStr);
        return resultStr;
    }

    /**
     * base64字符串转换成图片
     * @param imgStr		base64字符串
     * @param imgFilePath	图片存放路径
     * @return
     *
     * @author anxiang
     * @dateTime 2018-02-23 14:42:17
     */
    public boolean Base64ToImage(String imgStr,String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片

        if (StringEx.isNull(imgStr) || StringEx.isNull(imgFilePath)){// 图像数据为空
            return false;
        }
        File file = new File(imgFilePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }


        if(imgStr.contains("base64,")){
            imgStr = imgStr.substring(imgStr.indexOf("base64,")+7,imgStr.length());
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();

            return true;
        } catch (Exception e) {
            return false;
        }

    }
}
